package cn.kgc.service.impl;

import cn.kgc.client.RestDmImageClient;
import cn.kgc.client.RestDmUserClient;
import cn.kgc.config.WxConfig;
import cn.kgc.dto.Dto;
import cn.kgc.pojo.DmImage;
import cn.kgc.pojo.DmUser;
import cn.kgc.service.WxService;
import cn.kgc.util.RedisUtil;
import cn.kgc.utils.Constants;
import cn.kgc.utils.EmptyUtils;
import cn.kgc.utils.HttpclientUtils;
import cn.kgc.utils.UrlUtils;
import cn.kgc.vo.DmUserVO;
import cn.kgc.vo.TokenVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class WxServiceImpl implements WxService {


    @Autowired
    WxConfig wxConfig;


    @Autowired
    private RestDmUserClient restDmUserClient;

    @Autowired
    private RestDmImageClient restDmImageClient;

    @Autowired
    private RedisUtil redisUtils;




    @Override
    public DmUserVO loadCurrentUserByTokenAsDmUserVo(String tokenString) throws Exception {
        String tokenUser = null;
        if ((tokenUser = (String) redisUtils.get(tokenString)) == null) {
            //抛出异常
            return null;
        }
        return JSONObject.parseObject(tokenUser, DmUserVO.class);
    }

    private void saveToken(String token, DmUserVO dmUserVO) {
        String tokenKey = Constants.USER_TOKEN_PREFIX + dmUserVO.getUserId();
        String tokenValue = null;
        //检查是否已经登陆，如果还在登陆有效期内，就需要删除掉原来的登陆信息
        if ((tokenValue = (String) redisUtils.get(tokenKey)) != null) {
            //代表原来用户已经登陆
            redisUtils.del(tokenKey);
        }
        //缓存用户token
        redisUtils.set(tokenKey,  token,Constants.Redis_Expire.SESSION_TIMEOUT);
        //缓存用户详细信息
        redisUtils.set(token, JSON.toJSONString(dmUserVO), Constants.Redis_Expire.SESSION_TIMEOUT);
    }

    private String generateToken(DmUser dmUser) throws Exception{
        return restDmUserClient.generateToken(dmUser);
    }

    @Override
    public String wechatLogin(Map<String, Object> userInfoMap, String openId) throws Exception {
        //获取微信用户信息入库——用户昵称
        String nickName = userInfoMap.get("nickname").toString();
        //获取微信用户信息入库——用户性别
        String sex = userInfoMap.get("sex").toString();
        //获取微信用户信息入库——用户头像
        String headimgurl = userInfoMap.get("headimgurl").toString();

        //判断是否已经入库
        Map<String, Object> map = new HashMap<>();
        map.put("wxUserId",openId);

        DmUser dmUser =null;
        List<DmUser> dmUserListByMap = restDmUserClient.getDmUserListByMap(map);
        if (dmUserListByMap.size()!=0) {
            dmUser=dmUserListByMap.get(0);
        }
        //dmUser为null，则进行入库操作
        Long userId = 0L;
        if(EmptyUtils.isEmpty(dmUser)){
            dmUser = new DmUser();
            dmUser.setNickName(nickName);
            dmUser.setSex(Integer.parseInt(sex));
            dmUser.setWxUserId(openId);
            //添加用户
            userId = new Long(restDmUserClient.qdtxAddDmUser(dmUser));

            //插入头像信息  targetId(userId)   type(0)  category(0)
            //调用dm-base-provider 模块插入图片数据

        }

        DmUserVO dmUserVO = new DmUserVO();
        BeanUtils.copyProperties(dmUser, dmUserVO);
        dmUserVO.setUserId(userId);
        //获取用户的头像
        // 1.从redis里面获取的
        String key = Constants.IMAGE_TOKEN_PREFIX + userId.toString()
                + "_" + Constants.Image.ImageType.normal
                + "_" + Constants.Image.ImageCategory.user;
        String imgUrl = (String)redisUtils.get(key);
        List<DmImage> dmImages = new ArrayList<DmImage>();
        if(EmptyUtils.isEmpty(imgUrl)){
            dmImages = restDmImageClient.getDmImage_DefaultImage(userId,
                    Constants.Image.ImageType.normal,
                    Constants.Image.ImageCategory.user);
            if(EmptyUtils.isNotEmpty(dmImages)){
                String imgUrlStr = dmImages.get(0).getImgUrl();
                if(Constants.DEFAULT_USER.equals(imgUrlStr)){
                    //将用户头像缓存到redis中
                    redisUtils.set(key, headimgurl);
                    dmUserVO.setImgUrl(headimgurl);
                    //将用户的头像入库
                    DmImage dmImage = new DmImage();
                    dmImage.setTargetId(Integer.parseInt(userId.toString()));
                    dmImage.setCategory(Constants.Image.ImageCategory.user);
                    dmImage.setType(Constants.Image.ImageType.normal);
                    restDmImageClient.qdtxAddDmImage(dmImage);
                }else{
                    dmUserVO.setImgUrl(imgUrlStr);
                    redisUtils.set(key, imgUrlStr);
                }
            }
        }else{
            dmUserVO.setImgUrl(imgUrl);
        }
        dmUserVO.setUserId(userId);
        //生成token
        String token = this.generateToken(dmUser);
        //缓存用户信息到redis中
        this.saveToken(token, dmUserVO);
        return token;
    }
}
